<?php

// 佣金

namespace app\shop\controller;

use think\Db;
use think\Session;
use think\Request;
use think\Controller;
use think\Exception;
use app\shop\model\MemberDistribution;
use app\shop\model\Member as MemberModel;
use app\mobile\model\CashWithdrawal;
use app\shop\model\MemberBrokerage as MemberBrokerageModel;
use app\shop\model\MemberDistribution as MemberDistributionModel;
use app\shop\model\MemberDistributionOrder as MemberDistributionOrderModel;

class Commission extends Controller
{
    /**
     * 佣金
     * @return mixed
     */
    public function index()
    {
        $type = Request::instance()->param('type',1);
        // 实例化
        $memberBrokerage = new MemberBrokerageModel();
        $memberDistribution = new MemberDistributionModel();
        $memberDistributionOrder = new MemberDistributionOrderModel();
        $memberId = Session::get('member_id');


        $result = $memberBrokerage->where('member_id', $memberId)->find();


        // 查看用户当前层级 (用于查找下2级分润会员)
        $level = $memberDistribution->where('referrals_id', $memberId)->value('level');

        // 分销商人总数 (自己下两级)
        $result['distribution'] = $memberDistribution->where(['hierarchy' => ['like', '%,' . $memberId . ',%'], 'level' => ['elt', $level + 2]])->count();

        //查找分销会员id
        $result['distribution_ids'] = $memberDistribution->where(['hierarchy' => ['like', '%' . $memberId . '%']])->column('referrals_id');

        $result['distribution_order_count'] = 0;

        //所有下2级分销商
        $data = (new MemberDistribution())->where(['sun_member_distribution.level' => ['elt', ($level + 2)], 'sun_member_distribution.hierarchy' => ['like', '%,' . $memberId . ',%']])
            ->with(['member', 'memberDistributionOrder' => function ($e) {
                //分销订单上级会员id是当前会员
                $e->where('distribution_id', Session::get('member_id'));
            }])->order(['create_time' => 'desc'])->select();

        //去除没有会员信息和分销订单的数据
        $num = 0;
        if ($data) {
            foreach ($data as $key => &$item) {
                if (!$item->member || !$item->memberDistributionOrder) {
                    unset($data[$key]);
                } else {
                    foreach ($item->memberDistributionOrder as $o) {
                        //分销订单关联会员已产生佣金的订单
                        $o->memberOrder;
                    }
                    foreach ($item->memberDistributionOrder as $_key => $_item) {
                        if (!is_null($_item->memberOrder)) {
                            $num++;
                        }
                    }
                }
            }
        }
        //分销会员的订单数量 (按店铺计)
        $result['distribution_order_count'] = $num;

        //分销会员收入的佣金
        $distribution_brokerage = (new $memberDistributionOrder())
            ->where([
                'sun_member_distribution_order.member_id'       => ['in', implode(',', $result['distribution_ids'])],
                'sun_member_distribution_order.distribution_id' => $memberId,
            ])->with(['memberOrder'])->select();

        $result['distribution_brokerage'] = "0.00";
        $result['distribution_to_yield'] = "0.00";
        if ($distribution_brokerage) {
            foreach ($distribution_brokerage as $value) {
                if ($value->memberOrder) {
                    //下级返给本人已收益
                    if (in_array($value->memberOrder->status, [3, 4])) {
                        $result['distribution_brokerage'] = bcadd($result['distribution_brokerage'], $value->brokerage, 2);
                        //下级返给本人待收益
                    } else if (in_array($value->memberOrder->status, [0, 1, 2])) {
                        $result['distribution_to_yield'] = bcadd($result['distribution_to_yield'], $value->brokerage, 2);
                    }
                }
            }
        }

        //本人周周币(自己买的已收益的)
        $result['self_general_income'] = bcsub(bcsub($result['general_income'], $result['to_yield'], 2), $result['distribution_brokerage'], 2);

        //周周币总收入
        $result['total_money'] = bcadd($result['distribution_brokerage'], $result['general_income'], 2);

        //本人待收益合计
        $result['self_to_yield'] = bcsub($result['to_yield'], $result['distribution_to_yield'], 2);

        //待审核合计
        $result['total_to_audit'] = $memberBrokerage->where('member_id', 'in', implode(',', $result['distribution_ids']) . ',' . $memberId)->sum('to_audit');

        $order = "";
        if ($type==1) {
            $order = self::order_view();
        }else{
            $order = self::cash();
        }



        return $this->fetch('', [
            'mate_head' => '我的余额',
            'result'    => $result,
            'order'     => $order,
        ]);


    }


    /**
     * 分销订单  (下级分销订单)
     */
    public function order_view()
    {
        $ini = ['sun_member_distribution_order.distribution_id' => Session::get('member_id')];

        $result = (new MemberDistributionOrderModel())->where($ini)
            ->with(['memberDistribution', 'memberOrderList' => function ($e) {
                $condition = ['status' => ['in', '3,4']];
                $e->where($condition)->withField('id,status,price,shop_order_number,create_time,freight');
            }])->order('create_time desc')->select();
        $arr = [];
       if ($result) {
           foreach ($result as $value) {
               if ($value['brokerage'] != "0.00") {
                   $arr[]=$value;
               }
           }
       }


        return $arr;
    }


    public function cash()
    {
        $cash = (new CashWithdrawal)->where('member_id',Session::get('member_id'))->order('create_time desc')->select();
        $result = "";
        foreach ($cash as $value) {
            if ($value['type_id'] == 1) {
                $result[] = [
                    'title' => '佣金提现到余额',
                    'create_time' => date('Y-m-d',$value['create_time']),
                    'brokerage'  => $value['cash'],
                    'order_number' => '',
                ];
            }else{
                $result[] = [
                    'title' => '佣金提现第三方账户',
                    'create_time' => date('Y-m-d',$value['create_time']),
                    'brokerage'  => $value['cash'],
                    'order_number' => '',
                ];
            }
    }
        return $result;
    }


    /*
     * 佣金提现到余额
     */
    public function withdrawals()
    {
        $user_id = Session::get('member_id');
        // 个人信息
        $balance = (new MemberModel())->where(['id' => $user_id])->value('balance');
        // 会员佣金
        $brokerage = (new MemberBrokerageModel())->where(['member_id' => $user_id])->find();

        if (Request::instance()->isPost()) {
            // 获取参数
            $price = Request::instance()->param('price');

            if (empty($user_id)) throw new Exception('not Empty');


            // 提现金额大于一
            if ($price < 1) {
                return ['code' => 402, 'message' => '提现金额必须大于1元！'];
            }

            // 用户之前佣金余额
            $amount = (new MemberBrokerageModel)->where(['member_id' => $user_id])->value('actual_amount');

            if ($amount < $price) return ['code' => 402, 'message' => '佣金余额不足'];


            // 启动事务
            Db::startTrans();
            try {

                // 生成订单号
                $order_number = $this->createNumber();

                $information = [
                    'member_id'   => $user_id,
                    'type_id'     => 1,
                    'way'         => '提现到余额',
                    'account'     => '余额账户',
                    'status'      => 1,
                    'cash'        => $price,
                    'create_time' => time()
                ];

                $sisn = [
                    'member_id'    => $user_id,
                    'type_id'      => 2,
                    'price'        => $price,
                    'way'          => '佣金提现到余额',
                    'name'         => '',
                    'real_name'    => '',
                    'account'      => '',
                    'balance'      => $balance + $price,
                    'status'       => 1,
                    'reason'       => '',
                    'order_number' => $order_number,
                    'create_time'  => time(),
                ];

                // 添加成功
                Db::name('member_withdraw')->insert($sisn);
                Db::name('cash_withdrawal')->insert($information);
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setDec('actual_amount', $price);
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setDec('general_income', $price);
                Db::name('member')->where(['id' => $user_id])->setInc('balance', $price);

                // 提交事务
                Db::commit();

                return ['code' => 200, 'message' => '提现成功', 'order_number' => $order_number];

            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 401, 'message' => '网络繁忙,请重试'];
            }
        }



        return $this->fetch('', [
            'mate_head' => '提现到余额',
            'data'      => $balance,
            'brokerage' => $brokerage
        ]);


    }


    /*
     * 余额提现到银行卡
     */
    public function balance()
    {
        // 获取会员ID
        $user_id = Session::get('member_id');

        // 个人信息
        $result = (new MemberModel())->where(['id' => $user_id])->field('avatar,nickname,balance,integral,pay_pass,username,name,sex')->find();

        // 会员佣金
        $brokerage = (new MemberBrokerageModel())->where(['member_id' => $user_id])->find()->toArray();

        // 记录提现信息
        if (Request::instance()->isPost()) {
            $price = Request::instance()->param('price');
            $account = Request::instance()->param('account');
            $way = Request::instance()->param('way', '');

            if ($price<1) return ['code' => 402, 'message' => '提现金额必须大于1元'];

            // 判断提现金额是否充足
            if ($result['balance'] < $price) return ['code' => 402, 'message' => '余额不足'];

            // 启动事务
            Db::startTrans();

            try {

                $information = [
                    'member_id'   => $user_id,
                    'type_id'     => 2,
                    'way'         => $way,
                    'account'     => $account,
                    'status'      => 3,
                    'cash'        => $price,
                    'create_time' => time()
                ];


                // 添加成功

                Db::name('cash_withdrawal')->insert($information);
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setDec('actual_amount', $price);
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('to_audit', $price);
                // 提交事务
                Db::commit();

                return ['code'=>200,'message'=>'提现申请成功！'];

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ['code' => 401, 'message' => '网络繁忙'];
            }
        }


        return $this->fetch('', [
            'mate_head' => '我的提现',
            'result'    => $result,
            'brokerage' => $brokerage,
            'amount'    => $result['balance']
        ]);

    }


    /**
     * 生成订单号
     */
    protected function createNumber()
    {
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $order_id;
    }
}